package com.fyl.datasource.provider;


import com.fyl.datasource.config.DataSourceProperty;
import com.fyl.datasource.creator.DataSourceCreator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


public abstract class AbstractDataSourceProvider implements DataSourceProvider, InitializingBean {

    @Autowired
    private DataSourceCreator dataSourceCreator;

    protected Map<Object, Object> createDataSourceMap(Map<String, DataSourceProperty> dataSourcePropertiesMap) {
        Map<Object, Object> dataSourceMap = new HashMap<>(dataSourcePropertiesMap.size());
        for (Map.Entry<String, DataSourceProperty> item : dataSourcePropertiesMap.entrySet()) {
            String pollName = item.getKey();
            DataSourceProperty dataSourceProperty = item.getValue();
            dataSourceProperty.setPollName(pollName);
            dataSourceMap.put(pollName, dataSourceCreator.createDataSource(dataSourceProperty));
        }
        return dataSourceMap;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (Objects.isNull(dataSourceCreator)) {
            throw new IllegalArgumentException("Property 'dataSourceCreator' is required");
        }
    }

    public void setDataSourceCreator(DataSourceCreator dataSourceCreator) {
        this.dataSourceCreator = dataSourceCreator;
    }
}
